﻿Module Functions
    Function Split_Parameters(ByVal Args_String As String, ByRef Parameters As String(), ByRef Parameter_Values As String()) As Integer
        Dim arrArgs() As String
        Dim i As Integer = Args_String.LastIndexOf(")"c, Args_String.Length - 1, Args_String.Length)
        If i.Equals(-1) Then
            arrArgs = Args_String.Substring(Args_String.IndexOf("#"c, 0) + 1).Split("#"c)
        Else
            Dim Bra_Positions, Ket_Positions As New Stack(Of Integer)
            Bra_Positions.Push(Args_String.Length)
            While Not i.Equals(-1)
                Ket_Positions.Push(i)
                i = Args_String.LastIndexOf(")", i - 1, i)
            End While
            i = Args_String.LastIndexOf("("c, Args_String.Length - 1, Args_String.Length)
            While Not i.Equals(-1)
                Bra_Positions.Push(i)
                i = Args_String.LastIndexOf("(", i - 1, i)
            End While
            If Not Bra_Positions.Count - 1 = Ket_Positions.Count Then
                MsgBox("There are unpaired brackets in the porgamme arguments")
                Return -1
            End If
            Dim Current_Bra_Position As Integer = Bra_Positions.Peek
            Dim Current_Ket_Position As Integer = Args_String.IndexOf("#"c, 0) + 1
            arrArgs = Args_String.Substring(Current_Ket_Position, Current_Bra_Position - Current_Ket_Position).Split("#"c)
            While Ket_Positions.Count > 0
                Current_Bra_Position = Bra_Positions.Pop
                Current_Ket_Position = Ket_Positions.Peek
                'Dim nestling_levels As Short = 0
                While Bra_Positions.Peek < Current_Ket_Position
                    Bra_Positions.Pop()
                    Ket_Positions.Pop()
                    'nestling_levels = nestling_levels + 1
                End While
                Current_Ket_Position = Ket_Positions.Pop()
                arrArgs(arrArgs.Length - 1) = arrArgs(arrArgs.Length - 1) & Args_String.Substring(Current_Bra_Position, Current_Ket_Position - Current_Bra_Position + 1)
                Dim temp_arrArgs() As String
                temp_arrArgs = Args_String.Substring(Args_String.IndexOf("#"c, Current_Ket_Position) + 1, Bra_Positions.Peek - Args_String.IndexOf("#"c, Current_Ket_Position) - 1).Split("#"c)
                ReDim Preserve arrArgs(arrArgs.Length + temp_arrArgs.Length - 1)
                temp_arrArgs.CopyTo(arrArgs, arrArgs.Length - temp_arrArgs.Length)
            End While
        End If

        ReDim Parameters(arrArgs.Length - 1)
        ReDim Parameter_Values(arrArgs.Length - 1)

        For i = 0 To arrArgs.Length - 1
            Parameters(i) = arrArgs(i).Substring(0, arrArgs(i).IndexOf(" ", 0))
            Parameter_Values(i) = arrArgs(i).Substring(arrArgs(i).IndexOf(" ", 0) + 1, arrArgs(i).Length - Parameters(i).Length - 1)
        Next
        Return 0
    End Function
End Module
